package com.woniuxy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

/**
 * @Author: 马宇航
 * @Todo: TODO
 * @DateTime: 25/03/04/星期二 12:05
 * @Component: 成都蜗牛学苑
 **/
//@Configuration
//@EnableCaching //启用缓存
public class RedisConfig extends CachingConfigurerSupport {


    //RedisTemplate 配置
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        //由于Redis需要将传入的对象进行序列化与反序列化，所以需要做如下配置
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        //创建对象的映射
        ObjectMapper mapper = new ObjectMapper();
        //指定需要序列化的域：field getter() 当然也可以控制访问修饰符
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        serializer.setObjectMapper(mapper);
        //设置Key的序列化规则
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        //设置Value的序列化规则
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }

    //配置SpringCache整合redis 配置RedisCacheConfiguration bean对象
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        //使用默认缓存配置
        //配置序列化方案
        RedisCacheConfiguration   configuration = RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return configuration;
    }
}